<template>
  <div class="app-container">
    <!-- 导航栏 -->
    <nav class="navbar">
      <div class="logo">
        <div class="logo-icon">
          <el-icon><DataAnalysis /></el-icon>
        </div>
        <div class="logo-text">NEWBE工作室</div>
      </div>
      
      <ul class="nav-items">
        <li class="nav-item">
          <router-link to="/rfm-analysis" class="nav-link active">RFM客户行为分析</router-link>
        </li>
        <li class="nav-item">
          <router-link to="/customer-lifecycle" class="nav-link">客户生命周期</router-link>
        </li>
        <li class="nav-item">
          <router-link to="/marketing-analysis" class="nav-link">营销活动分析</router-link>
        </li>
        <li class="nav-item">
          <router-link to="/sales-prediction" class="nav-link">销售预测</router-link>
        </li>
      </ul>
      
      <div class="user-profile">
        <div class="user-avatar">{{ userInfo.nickname?.charAt(0)?.toUpperCase() || 'A' }}</div>
      </div>
    </nav>

    <!-- 返回按钮 -->
    <div class="back-button-container">
      <el-button 
        class="back-button" 
        type="primary" 
        size="small" 
        @click="goBack"
      >
        <el-icon><Back /></el-icon>
        返回工作台
      </el-button>
    </div>

    <!-- 主要内容区域 -->
    <div class="content-wrapper">
      <div class="container">
        <!-- 标题和刷新按钮 -->
        <div class="header">
          <h1 class="title">RFM客户行为分析</h1>
          <el-button type="primary" class="refresh-btn" @click="generateAnalysis">
            <el-icon><Refresh /></el-icon>
            生成分析
          </el-button>
        </div>
        
        <!-- 数据统计卡片 -->
        <div class="stats-cards">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-value">{{ summaryData.total_customers }}</div>
            <div class="stat-label">客户总数</div>
            <div :class="['stat-change', summaryData.customer_growth >= 0 ? 'positive' : 'negative']">
              <el-icon v-if="summaryData.customer_growth >= 0"><ArrowUp /></el-icon>
              <el-icon v-else><ArrowDown /></el-icon>
              {{ Math.abs(summaryData.customer_growth).toFixed(1) }}% 较上月
            </div>
          </div>
          
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><UserPlus /></el-icon>
            </div>
            <div class="stat-value">{{ summaryData.new_customers_30days }}</div>
            <div class="stat-label">近30天新增</div>
            <div :class="['stat-change', summaryData.new_customer_growth >= 0 ? 'positive' : 'negative']">
              <el-icon v-if="summaryData.new_customer_growth >= 0"><ArrowUp /></el-icon>
              <el-icon v-else><ArrowDown /></el-icon>
              {{ Math.abs(summaryData.new_customer_growth).toFixed(1) }}% 较上月
            </div>
          </div>
          
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-value">¥{{ summaryData.avg_customer_value.toLocaleString() }}</div>
            <div class="stat-label">客户平均价值</div>
            <div :class="['stat-change', summaryData.avg_value_growth >= 0 ? 'positive' : 'negative']">
              <el-icon v-if="summaryData.avg_value_growth >= 0"><ArrowUp /></el-icon>
              <el-icon v-else><ArrowDown /></el-icon>
              {{ Math.abs(summaryData.avg_value_growth).toFixed(1) }}% 较上月
            </div>
          </div>
          
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><RefreshRight /></el-icon>
            </div>
            <div class="stat-value">{{ summaryData.repeat_purchase_rate }}%</div>
            <div class="stat-label">客户复购率</div>
            <div :class="['stat-change', summaryData.repeat_rate_growth >= 0 ? 'positive' : 'negative']">
              <el-icon v-if="summaryData.repeat_rate_growth >= 0"><ArrowUp /></el-icon>
              <el-icon v-else><ArrowDown /></el-icon>
              {{ Math.abs(summaryData.repeat_rate_growth).toFixed(1) }}% 较上月
            </div>
          </div>
        </div>
        
        <!-- 图表区域 -->
        <div class="charts-section">
          <!-- 客户价值矩阵图表 -->
          <div class="chart-card">
            <div class="chart-header">
              <h3 class="chart-title">客户价值矩阵</h3>
            </div>
            <div class="chart-container" ref="valueMatrixChartRef"></div>
          </div>
          
          <!-- 客户类型分布图表 -->
          <div class="chart-card">
            <div class="chart-header">
              <h3 class="chart-title">客户类型分布</h3>
            </div>
            <div class="chart-container" ref="customerTypeChartRef"></div>
          </div>
          
          <!-- RFM趋势图表 -->
          <div class="chart-card">
            <div class="chart-header">
              <h3 class="chart-title">RFM趋势分析</h3>
            </div>
            <div class="chart-container" ref="rfmTrendsChartRef"></div>
          </div>
          
          <!-- 客户生命周期阶段分析 -->
          <div class="chart-card">
            <div class="chart-header">
              <h3 class="chart-title">客户生命周期阶段分析</h3>
            </div>
            <div class="chart-container" ref="lifecycleChartRef"></div>
          </div>
          
          <!-- 消费金额分布 - 全宽显示 -->
          <div class="chart-card full-width">
            <div class="chart-header">
              <h3 class="chart-title">消费金额分布</h3>
            </div>
            <div class="chart-container" ref="monetaryDistributionChartRef"></div>
          </div>
        </div>
        
        <!-- RFM分析结果表格 -->
        <div class="table-section">
          <div class="table-header">
            <h3 class="table-title">RFM客户分析结果</h3>
            <div class="search-box">
              <el-input
                v-model="searchQuery"
                placeholder="搜索客户"
                prefix-icon="Search"
                clearable
                @clear="handleSearch"
                @keyup.enter="handleSearch"
              />
            </div>
          </div>
          
          <el-table
            :data="rfmResults"
            style="width: 100%"
            border
            stripe
            v-loading="tableLoading"
            :header-cell-style="{
              fontWeight: '600',
              background: 'rgba(58, 54, 219, 0.15)',
              color: '#00c9ff'
            }"
          >
            <el-table-column prop="customer_name" label="客户名称" min-width="180" show-overflow-tooltip />
            <el-table-column prop="days_since_last_purchase" label="最近购买(天)" min-width="120">
              <template #default="scope">
                <span class="highlight-text">{{ scope.row.days_since_last_purchase }}</span> 天
              </template>
            </el-table-column>
            <el-table-column prop="purchase_count" label="购买频率" min-width="100">
              <template #default="scope">
                <span class="highlight-text">{{ scope.row.purchase_count }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="total_amount" label="消费金额" min-width="120">
              <template #default="scope">
                <span class="money-text">¥{{ Number(scope.row.total_amount).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2}) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="r_score" label="R分数" min-width="80">
              <template #default="scope">
                <span class="score-text r-score">{{ scope.row.r_score }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="f_score" label="F分数" min-width="80">
              <template #default="scope">
                <span class="score-text f-score">{{ scope.row.f_score }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="m_score" label="M分数" min-width="80">
              <template #default="scope">
                <span class="score-text m-score">{{ scope.row.m_score }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="rfm_score" label="RFM总分" min-width="100">
              <template #default="scope">
                <span class="score-text total-score">{{ scope.row.rfm_score }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="customer_type" label="客户类型" min-width="150">
              <template #default="scope">
                <el-tag :type="getCustomerTypeTagType(scope.row.customer_type)">
                  {{ scope.row.customer_type }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="customer_value" label="客户价值" min-width="120">
              <template #default="scope">
                <el-tag :type="getCustomerValueTagType(scope.row.customer_value)">
                  {{ scope.row.customer_value }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalItems"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              background
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, reactive, computed } from 'vue';
import { User, UserPlus, Money, RefreshRight, ArrowUp, ArrowDown, Refresh, DataAnalysis, Back } from '@element-plus/icons-vue';
import { 
  getRfmSummary, 
  getRfmMatrix, 
  getCustomerTypes, 
  getRfmAnalysisResults,
  getRfmTrends,
  getCustomerLifecycle,
  getMonetaryDistribution
} from '@/api/rfm-analysis';
import * as echarts from 'echarts/core';
import { GridComponent, TooltipComponent, LegendComponent, VisualMapComponent } from 'echarts/components';
import { HeatmapChart, PieChart, LineChart, BarChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';
import { ElMessage, ElLoading } from 'element-plus';
import { useUserStore } from '@/stores/user';

// 获取用户信息
const userStore = useUserStore();
const userInfo = computed(() => userStore.userInfo);

// 注册echarts组件
echarts.use([
  GridComponent,
  TooltipComponent,
  LegendComponent,
  VisualMapComponent,
  HeatmapChart,
  PieChart,
  LineChart,
  BarChart,
  CanvasRenderer
]);

// 图表引用
const valueMatrixChartRef = ref(null);
const customerTypeChartRef = ref(null);
const rfmTrendsChartRef = ref(null);
const lifecycleChartRef = ref(null);
const monetaryDistributionChartRef = ref(null);

let valueMatrixChart = null;
let customerTypeChart = null;
let rfmTrendsChart = null;
let lifecycleChart = null;
let monetaryDistributionChart = null;

// 数据
const summaryData = reactive({
  total_customers: 0,
  new_customers_30days: 0,
  avg_customer_value: 0,
  repeat_purchase_rate: 0,
  customer_growth: 0,
  new_customer_growth: 0,
  avg_value_growth: 0,
  repeat_rate_growth: 0
});

const rfmResults = ref([]);
const tableLoading = ref(false);
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const totalItems = ref(0);

// 初始化
onMounted(() => {
  initCharts();
  fetchAllData();
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize);
  
  // 销毁图表
  if (valueMatrixChart) {
    valueMatrixChart.dispose();
    valueMatrixChart = null;
  }
  
  if (customerTypeChart) {
    customerTypeChart.dispose();
    customerTypeChart = null;
  }
  
  if (rfmTrendsChart) {
    rfmTrendsChart.dispose();
    rfmTrendsChart = null;
  }
  
  if (lifecycleChart) {
    lifecycleChart.dispose();
    lifecycleChart = null;
  }
  
  if (monetaryDistributionChart) {
    monetaryDistributionChart.dispose();
    monetaryDistributionChart = null;
  }
});

// 初始化图表
const initCharts = () => {
  // 初始化客户价值矩阵图表
  valueMatrixChart = echarts.init(valueMatrixChartRef.value);
  
  // 初始化客户类型分布图表
  customerTypeChart = echarts.init(customerTypeChartRef.value);
  
  // 初始化RFM趋势图表
  rfmTrendsChart = echarts.init(rfmTrendsChartRef.value);
  
  // 初始化客户生命周期图表
  lifecycleChart = echarts.init(lifecycleChartRef.value);
  
  // 初始化消费金额分布图表
  monetaryDistributionChart = echarts.init(monetaryDistributionChartRef.value);
  
  // 设置初始配置
  setValueMatrixChartOption([]);
  setCustomerTypeChartOption([]);
  setRfmTrendsChartOption([]);
  setLifecycleChartOption([]);
  setMonetaryDistributionChartOption([]);
};

// 处理窗口大小变化
const handleResize = () => {
  if (valueMatrixChart) {
    valueMatrixChart.resize();
  }
  
  if (customerTypeChart) {
    customerTypeChart.resize();
  }
  
  if (rfmTrendsChart) {
    rfmTrendsChart.resize();
  }
  
  if (lifecycleChart) {
    lifecycleChart.resize();
  }
  
  if (monetaryDistributionChart) {
    monetaryDistributionChart.resize();
  }
};

// 获取所有数据
const fetchAllData = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '加载RFM分析数据...',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  
  try {
    // 一个一个调用API，而不是使用Promise.all，这样可以更容易定位问题
    try {
      await fetchSummaryData();
      console.log('概览数据加载成功');
    } catch (error) {
      console.error('获取概览数据失败:', error.response?.data || error.message);
      ElMessage.error('获取概览数据失败: ' + (error.response?.data?.detail || error.message));
    }
    
    try {
      await fetchMatrixData();
      console.log('矩阵数据加载成功');
    } catch (error) {
      console.error('获取矩阵数据失败:', error.response?.data || error.message);
      ElMessage.error('获取矩阵数据失败: ' + (error.response?.data?.detail || error.message));
    }
    
    try {
      await fetchCustomerTypesData();
      console.log('客户类型数据加载成功');
    } catch (error) {
      console.error('获取客户类型数据失败:', error.response?.data || error.message);
      ElMessage.error('获取客户类型数据失败: ' + (error.response?.data?.detail || error.message));
    }
    
    try {
      await fetchRfmResults();
      console.log('RFM分析结果加载成功');
    } catch (error) {
      console.error('获取RFM分析结果失败:', error.response?.data || error.message);
      ElMessage.error('获取RFM分析结果失败: ' + (error.response?.data?.detail || error.message));
    }
    
    // 新增的三个图表数据获取
    try {
      await fetchRfmTrendsData();
      console.log('RFM趋势数据加载成功');
    } catch (error) {
      console.error('获取RFM趋势数据失败:', error.response?.data || error.message);
      ElMessage.error('获取RFM趋势数据失败: ' + (error.response?.data?.detail || error.message));
    }
    
    try {
      await fetchLifecycleData();
      console.log('客户生命周期数据加载成功');
    } catch (error) {
      console.error('获取客户生命周期数据失败:', error.response?.data || error.message);
      ElMessage.error('获取客户生命周期数据失败: ' + (error.response?.data?.detail || error.message));
    }
    
    try {
      await fetchMonetaryDistributionData();
      console.log('消费金额分布数据加载成功');
    } catch (error) {
      console.error('获取消费金额分布数据失败:', error.response?.data || error.message);
      ElMessage.error('获取消费金额分布数据失败: ' + (error.response?.data?.detail || error.message));
    }
    
    ElMessage.success('RFM分析数据加载完成');
  } catch (error) {
    console.error('加载RFM分析数据出错:', error);
    ElMessage.error('加载RFM分析数据失败，请稍后重试');
  } finally {
    loading.close();
  }
};

// 生成分析
const generateAnalysis = () => {
  fetchAllData();
};

// 获取概览数据
const fetchSummaryData = async () => {
  try {
    console.log('开始获取RFM概览数据');
    const response = await getRfmSummary();
    console.log('RFM概览数据原始响应:', response);
    
    // 优先使用response.data，如果不存在则使用response本身
    const data = response.data !== undefined ? response.data : response;
    console.log('处理后的RFM概览数据:', data);
    
    // 更新概览数据
    Object.assign(summaryData, data);
  } catch (error) {
    console.error('获取RFM概览数据失败:', error);
    throw error;
  }
};

// 获取矩阵数据
const fetchMatrixData = async () => {
  try {
    console.log('开始获取RFM矩阵数据');
    const response = await getRfmMatrix();
    console.log('RFM矩阵数据原始响应:', response);
    
    // 优先使用response.data，如果不存在则使用response本身
    const data = response.data !== undefined ? response.data : response;
    console.log('处理后的RFM矩阵数据:', data);
    
    // 更新矩阵图表
    setValueMatrixChartOption(data);
  } catch (error) {
    console.error('获取RFM矩阵数据失败:', error);
    throw error;
  }
};

// 获取客户类型分布数据
const fetchCustomerTypesData = async () => {
  try {
    console.log('开始获取客户类型分布数据');
    const response = await getCustomerTypes();
    console.log('客户类型分布数据原始响应:', response);
    
    // 优先使用response.data，如果不存在则使用response本身
    const data = response.data !== undefined ? response.data : response;
    console.log('处理后的客户类型分布数据:', data);
    
    // 检查数据是否为空或无效
    if (!data || !Array.isArray(data)) {
      console.warn('获取到的客户类型分布数据无效，使用默认空数组');
      setCustomerTypeChartOption([]);
      return;
    }
    
    // 更新客户类型分布图表
    setCustomerTypeChartOption(data);
  } catch (error) {
    console.error('获取客户类型分布数据失败:', error);
    throw error;
  }
};

// 获取RFM分析结果
const fetchRfmResults = async () => {
  tableLoading.value = true;
  
  try {
    console.log('开始获取RFM分析结果');
    const response = await getRfmAnalysisResults({
      page: currentPage.value,
      page_size: pageSize.value,
      search: searchQuery.value
    });
    console.log('RFM分析结果原始响应:', response);
    
    // 优先使用response.data，如果不存在则使用response本身
    const data = response.data !== undefined ? response.data : response;
    console.log('处理后的RFM分析结果:', data);
    
    // 检查数据结构是否符合预期
    if (data && data.results) {
      rfmResults.value = data.results;
      totalItems.value = data.pagination.total;
    } else {
      console.warn('获取到的RFM分析结果数据格式不符合预期');
      rfmResults.value = [];
      totalItems.value = 0;
    }
  } catch (error) {
    console.error('获取RFM分析结果失败:', error);
    throw error;
  } finally {
    tableLoading.value = false;
  }
};

// 获取RFM趋势数据
const fetchRfmTrendsData = async () => {
  try {
    console.log('开始获取RFM趋势数据');
    const response = await getRfmTrends();
    console.log('RFM趋势数据原始响应:', response);
    
    // 优先使用response.data，如果不存在则使用response本身
    const data = response.data !== undefined ? response.data : response;
    console.log('处理后的RFM趋势数据:', data);
    
    // 更新趋势图表
    setRfmTrendsChartOption(data);
  } catch (error) {
    console.error('获取RFM趋势数据失败:', error);
    throw error;
  }
};

// 获取客户生命周期阶段数据
const fetchLifecycleData = async () => {
  try {
    console.log('开始获取客户生命周期数据');
    const response = await getCustomerLifecycle();
    console.log('客户生命周期数据原始响应:', response);
    
    // 优先使用response.data，如果不存在则使用response本身
    const data = response.data !== undefined ? response.data : response;
    console.log('处理后的客户生命周期数据:', data);
    
    // 更新生命周期图表
    setLifecycleChartOption(data);
  } catch (error) {
    console.error('获取客户生命周期数据失败:', error);
    throw error;
  }
};

// 获取消费金额分布数据
const fetchMonetaryDistributionData = async () => {
  try {
    console.log('开始获取消费金额分布数据');
    const response = await getMonetaryDistribution();
    console.log('消费金额分布数据原始响应:', response);
    
    // 优先使用response.data，如果不存在则使用response本身
    const data = response.data !== undefined ? response.data : response;
    console.log('处理后的消费金额分布数据:', data);
    
    // 更新消费金额分布图表
    setMonetaryDistributionChartOption(data);
  } catch (error) {
    console.error('获取消费金额分布数据失败:', error);
    throw error;
  }
};

// 设置客户价值矩阵图表配置
const setValueMatrixChartOption = (data) => {
  const option = {
    tooltip: {
      position: 'top',
      formatter: function (params) {
        return `${params.data[2]} 个客户`;
      }
    },
    grid: {
      left: '10%',
      right: '10%',
      top: '15%',
      bottom: '15%'
    },
    xAxis: {
      type: 'category',
      data: ['低', '中', '高'],
      splitArea: {
        show: true
      },
      name: '消费频率(F)',
      nameLocation: 'middle',
      nameGap: 30,
      axisLabel: {
        fontWeight: 'bold',
        color: '#e0e0ff'
      },
      axisLine: {
        lineStyle: {
          color: '#2a2a57'
        }
      }
    },
    yAxis: {
      type: 'category',
      data: ['高', '中', '低'],
      splitArea: {
        show: true
      },
      name: '消费金额(M)',
      nameLocation: 'middle',
      nameGap: 30,
      axisLabel: {
        fontWeight: 'bold',
        color: '#e0e0ff'
      },
      axisLine: {
        lineStyle: {
          color: '#2a2a57'
        }
      }
    },
    visualMap: {
      min: 0,
      max: 20,
      calculable: true,
      orient: 'horizontal',
      left: 'center',
      bottom: '0%',
      inRange: {
        color: ['#13142a', '#3a36db', '#00c9ff', '#00ffb3']
      },
      textStyle: {
        color: '#e0e0ff'
      }
    },
    series: [{
      name: '客户分布',
      type: 'heatmap',
      data: data || [],
      label: {
        show: true,
        color: '#fff'
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowColor: 'rgba(0, 201, 255, 0.5)'
        }
      }
    }]
  };
  
  valueMatrixChart.setOption(option);
};

// 设置客户类型分布图表配置
const setCustomerTypeChartOption = (data) => {
  // 确保data是数组
  const chartData = Array.isArray(data) ? data : [];
  console.log('设置客户类型图表数据:', chartData);
  
  // 准备图例数据
  const legendData = chartData.length > 0 
    ? chartData.map(item => item.name || '未分类')
    : ['暂无数据'];
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: legendData,
      textStyle: {
        color: '#e0e0ff'
      }
    },
    series: [
      {
        name: '客户类型',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#13142a',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: chartData.length > 0 ? chartData : [
          { name: '暂无数据', value: 1, itemStyle: { color: '#cccccc' } }
        ]
      }
    ]
  };
  
  customerTypeChart.setOption(option);
};

// 设置RFM趋势图表配置
const setRfmTrendsChartOption = (data) => {
  const chartData = Array.isArray(data) ? data : [];
  
  // 如果没有数据，提供默认空数据
  if (chartData.length === 0) {
    // 生成6个月的默认数据
    for (let i = 0; i < 6; i++) {
      const date = new Date();
      date.setMonth(date.getMonth() - (5 - i));
      chartData.push({
        month: date.getFullYear() + '-' + (date.getMonth() + 1).toString().padStart(2, '0'),
        r_score: 0,
        f_score: 0,
        m_score: 0
      });
    }
  }
  
  // 提取月份作为X轴
  const months = chartData.map(item => item.month);
  
  // 提取三个指标的值构成系列数据
  const rScores = chartData.map(item => item.r_score);
  const fScores = chartData.map(item => item.f_score);
  const mScores = chartData.map(item => item.m_score);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        let result = params[0].name + '<br/>';
        params.forEach(param => {
          const marker = `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${param.color};"></span>`;
          result += marker + param.seriesName + ': ' + param.value + '<br/>';
        });
        return result;
      }
    },
    legend: {
      data: ['R指标', 'F指标', 'M指标'],
      textStyle: {
        color: '#e0e0ff'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: months,
      axisLabel: {
        color: '#e0e0ff'
      },
      axisLine: {
        lineStyle: {
          color: '#2a2a57'
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '得分',
      min: 0,
      max: 5,
      axisLabel: {
        color: '#e0e0ff'
      },
      axisLine: {
        lineStyle: {
          color: '#2a2a57'
        }
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(42, 42, 87, 0.3)'
        }
      }
    },
    series: [
      {
        name: 'R指标',
        type: 'line',
        data: rScores,
        lineStyle: {
          width: 3,
          color: '#00ffb3'
        },
        itemStyle: {
          color: '#00ffb3'
        },
        smooth: true
      },
      {
        name: 'F指标',
        type: 'line',
        data: fScores,
        lineStyle: {
          width: 3,
          color: '#00c9ff'
        },
        itemStyle: {
          color: '#00c9ff'
        },
        smooth: true
      },
      {
        name: 'M指标',
        type: 'line',
        data: mScores,
        lineStyle: {
          width: 3,
          color: '#3a36db'
        },
        itemStyle: {
          color: '#3a36db'
        },
        smooth: true
      }
    ]
  };
  
  rfmTrendsChart.setOption(option);
};

// 设置客户生命周期阶段图表配置
const setLifecycleChartOption = (data) => {
  const chartData = Array.isArray(data) ? data : [];
  
  // 如果没有数据提供默认空数据
  const defaultData = chartData.length > 0 ? chartData : [
    { name: '暂无数据', value: 1, itemStyle: { color: '#cccccc' } }
  ];
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: defaultData.map(item => item.name),
      textStyle: {
        color: '#e0e0ff'
      }
    },
    series: [
      {
        name: '客户生命周期',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#13142a',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: defaultData
      }
    ]
  };
  
  lifecycleChart.setOption(option);
};

// 设置消费金额分布图表配置
const setMonetaryDistributionChartOption = (data) => {
  const chartData = Array.isArray(data) ? data : [];
  
  // 如果没有数据提供默认空数据
  const defaultData = chartData.length > 0 ? chartData : [
    { name: '0-1000', value: 0, itemStyle: { color: '#00ffb3' } },
    { name: '1000-5000', value: 0, itemStyle: { color: '#3a36db' } },
    { name: '5000-10000', value: 0, itemStyle: { color: '#00c9ff' } },
    { name: '10000-50000', value: 0, itemStyle: { color: '#6236ff' } },
    { name: '50000+', value: 0, itemStyle: { color: '#ff9500' } }
  ];
  
  // 提取分类和值
  const categories = defaultData.map(item => item.name);
  const colors = defaultData.map(item => item.itemStyle.color);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}: {c} 个客户'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: categories,
      axisLabel: {
        color: '#e0e0ff'
      },
      axisLine: {
        lineStyle: {
          color: '#2a2a57'
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '客户数量',
      axisLabel: {
        color: '#e0e0ff'
      },
      axisLine: {
        lineStyle: {
          color: '#2a2a57'
        }
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(42, 42, 87, 0.3)'
        }
      }
    },
    series: [
      {
        name: '消费金额分布',
        type: 'bar',
        data: defaultData.map((item, index) => ({
          value: item.value,
          itemStyle: {
            color: colors[index]
          }
        })),
        barWidth: '50%',
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(0, 201, 255, 0.5)'
          }
        }
      }
    ]
  };
  
  monetaryDistributionChart.setOption(option);
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1; // 重置为第一页
  fetchRfmResults();
};

// 处理每页数量变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchRfmResults();
};

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchRfmResults();
};

// 获取客户类型标签类型
const getCustomerTypeTagType = (type) => {
  const typeMap = {
    '重要价值客户': 'success',
    '重要保持客户': 'success',
    '重要发展客户': 'warning',
    '重要挽留客户': 'danger',
    '一般价值客户': 'info',
    '一般保持客户': 'info',
    '一般发展客户': 'info',
    '一般挽留客户': 'info'
  };
  
  return typeMap[type] || 'info';
};

// 获取客户价值标签类型
const getCustomerValueTagType = (value) => {
  const valueMap = {
    '高价值': 'success',
    '中价值': 'warning',
    '低价值': 'info',
    '流失风险': 'danger'
  };
  
  return valueMap[value] || 'info';
};

// 返回工作台
function goBack() {
  window.location.href = 'dashboard#/dashboard';
}
</script>

<style>
html, body, #app {
  height: 100%;
  overflow: auto !important;
  min-height: 100vh;
}

.el-main {
  overflow-y: visible !important;
  height: auto !important;
}
</style>

<style scoped>
.app-container {
  --primary-color: #3a36db;
  --secondary-color: #00c9ff;
  --accent-color: #00ffb3;
  --dark-bg: #0a0b1a;
  --card-bg: #13142a;
  --text-color: #e0e0ff;
  --border-color: #2a2a57;
  --hover-color: #2d2d69;
  --gradient-primary: linear-gradient(135deg, #3a36db, #00c9ff);
  --gradient-secondary: linear-gradient(135deg, #00c9ff, #00ffb3);
  --box-shadow: 0 8px 32px rgba(0, 0, 201, 255, 0.1);
  
  background-color: var(--dark-bg);
  color: var(--text-color);
  min-height: 100vh;
  width: 100%;
  font-family: 'Roboto', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  position: relative;
  overflow-y: auto;
  height: auto;
}

.content-wrapper {
  width: 100%;
  overflow: visible;
  height: auto;
}

.app-container * {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Roboto', 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

/* 导航栏样式 */
.navbar {
  background-color: var(--card-bg);
  padding: 0.8rem 2rem;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  position: sticky;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid var(--border-color);
}

.logo {
  display: flex;
  align-items: center;
  gap: 0.8rem;
}

.logo-icon {
  width: 40px;
  height: 40px;
  background: var(--gradient-primary);
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
  box-shadow: 0 4px 15px rgba(58, 54, 219, 0.3);
}

.logo-text {
  font-size: 1.2rem;
  font-weight: 600;
  background: var(--gradient-primary);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.nav-items {
  display: flex;
  gap: 2.5rem;
  list-style: none;
}

.nav-item {
  position: relative;
}

.nav-link {
  color: var(--text-color);
  text-decoration: none;
  font-size: 1rem;
  font-weight: 500;
  padding: 0.5rem 0;
  transition: all 0.3s ease;
}

.nav-link.active {
  color: var(--secondary-color);
  font-weight: 600;
}

.nav-link.active::after {
  content: '';
  position: absolute;
  bottom: -5px;
  left: 0;
  width: 100%;
  height: 3px;
  background: var(--gradient-secondary);
  border-radius: 3px;
}

.nav-link:hover {
  color: var(--secondary-color);
}

.user-profile {
  display: flex;
  align-items: center;
  gap: 0.8rem;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: var(--gradient-secondary);
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--dark-bg);
  font-weight: bold;
}

/* 内容区域样式 */
.container {
  padding: 2rem;
  max-width: 1600px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.title {
  font-size: 1.8rem;
  font-weight: 700;
  background: var(--gradient-primary);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.refresh-btn {
  background: var(--gradient-primary);
  color: white;
  border: none;
  padding: 0.6rem 1.2rem;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(58, 54, 219, 0.3);
}

.refresh-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 25px rgba(58, 54, 219, 0.4);
}

/* 数据卡片组 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.stat-card {
  background-color: var(--card-bg);
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: var(--box-shadow);
  border: 1px solid var(--border-color);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 40px rgba(0, 201, 255, 0.15);
  border-color: var(--secondary-color);
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 100px;
  height: 100px;
  background: radial-gradient(circle at top right, rgba(0, 201, 255, 0.1), transparent 70%);
  border-radius: 50%;
}

.stat-icon {
  font-size: 1.5rem;
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
  margin-bottom: 1rem;
  background: rgba(58, 54, 219, 0.1);
  color: var(--secondary-color);
}

.stat-value {
  font-size: 2rem;
  font-weight: 700;
  margin-bottom: 0.5rem;
  background: var(--gradient-secondary);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.stat-label {
  font-size: 1rem;
  color: rgba(224, 224, 255, 0.8);
}

.stat-change {
  margin-top: 0.5rem;
  font-size: 0.875rem;
  display: flex;
  align-items: center;
  gap: 0.3rem;
}

.positive {
  color: var(--accent-color);
}

.negative {
  color: #ff6b6b;
}

/* 图表区域 */
.charts-section {
  margin-bottom: 2rem;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1.5rem;
}

/* 全宽图表样式 */
.chart-card.full-width {
  grid-column: 1 / -1; /* 从第一列跨到最后一列 */
}

/* 全宽图表的图表容器样式 */
.chart-card.full-width .chart-container {
  height: 450px; /* 增加全宽图表的高度 */
}

.chart-card {
  background-color: var(--card-bg);
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: var(--box-shadow);
  border: 1px solid var(--border-color);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.chart-title {
  font-size: 1.2rem;
  font-weight: 600;
}

.chart-container {
  height: 350px;
  width: 100%;
}

/* 表格区域 */
.table-section {
  background-color: var(--card-bg);
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: var(--box-shadow);
  border: 1px solid var(--border-color);
  margin-top: 2rem;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.table-title {
  font-size: 1.3rem;
  font-weight: 600;
  background: var(--gradient-primary);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.search-box {
  position: relative;
  width: 280px;
}

.pagination {
  margin-top: 1.5rem;
  display: flex;
  justify-content: flex-end;
}

/* 修复深度选择器语法为Vue 3兼容格式 */
:deep(.el-table) {
  background-color: transparent !important;
  color: var(--text-color) !important;
  border: none !important;
  font-size: 14px !important;
}

:deep(.el-table::before) {
  display: none;
}

:deep(.el-table::after) {
  display: none;
}

:deep(.el-table__inner-wrapper::before) {
  display: none;
}

:deep(.el-table__inner-wrapper) {
  border: none !important;
}

:deep(.el-table--border) {
  border: none !important;
  border-bottom: none !important;
}

:deep(.el-table--border::after) {
  display: none;
}

:deep(.el-table--border .el-table__inner-wrapper) {
  border-right: none !important;
  border-bottom: none !important;
}

:deep(.el-table th),
:deep(.el-table tr),
:deep(.el-table td) {
  background-color: transparent !important;
  color: var(--text-color) !important;
  border-color: rgba(42, 42, 87, 0.7) !important;
  padding: 12px 10px !important;
  transition: all 0.25s ease;
}

:deep(.el-table th) {
  background: rgba(58, 54, 219, 0.15) !important;
  font-weight: 600;
  color: var(--secondary-color) !important;
  font-size: 14px;
  padding: 15px 10px !important;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: rgba(42, 42, 87, 0.4) !important;
}

:deep(.el-table__body tr:hover > td) {
  background-color: var(--hover-color) !important;
  box-shadow: 0 0 10px rgba(0, 201, 255, 0.1);
}

:deep(.el-input__wrapper) {
  background-color: rgba(42, 42, 87, 0.4) !important;
  border-color: var(--border-color) !important;
  box-shadow: 0 0 0 1px var(--border-color) inset !important;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px var(--secondary-color) inset !important;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px var(--primary-color) inset !important;
}

:deep(.el-input__inner) {
  color: var(--text-color) !important;
}

:deep(.el-pagination) {
  --el-pagination-bg-color: transparent !important;
  --el-pagination-hover-color: var(--secondary-color) !important;
  --el-pagination-button-bg-color: rgba(42, 42, 87, 0.4) !important;
  --el-pagination-button-disabled-bg-color: rgba(42, 42, 87, 0.2) !important;
  --el-pagination-button-disabled-color: rgba(224, 224, 255, 0.5) !important;
  --el-pagination-border-color: var(--border-color) !important;
  --el-pagination-font-size: 14px !important;
  --el-text-color-primary: var(--text-color) !important;
  background-color: transparent !important;
}

:deep(.el-pagination.is-background .el-pager li) {
  background-color: rgba(42, 42, 87, 0.4) !important;
  color: var(--text-color) !important;
  border: 1px solid var(--border-color);
}

:deep(.el-pagination.is-background .el-pager li:not(.disabled).is-active) {
  background: var(--gradient-primary) !important;
  color: white !important;
  border-color: transparent !important;
}

:deep(.el-pagination .el-pagination__sizes .el-select .el-input) {
  --el-select-input-focus-border-color: var(--secondary-color) !important;
}

:deep(.el-pagination .el-pagination__sizes .el-select .el-input__wrapper) {
  background-color: rgba(42, 42, 87, 0.4) !important;
  box-shadow: 0 0 0 1px var(--border-color) inset !important;
}

:deep(.el-pagination .el-pagination__jump .el-input__wrapper) {
  background-color: rgba(42, 42, 87, 0.4) !important;
  box-shadow: 0 0 0 1px var(--border-color) inset !important;
}

:deep(.el-select .el-select__wrapper) {
  background-color: rgba(42, 42, 87, 0.4) !important;
}

:deep(.el-pagination .el-pager) {
  background-color: transparent !important; 
}

/* 修复弹出层和背景蒙层 */
:deep(.el-popper) {
  border: 1px solid var(--border-color) !important;
  background-color: var(--card-bg) !important;
}

:deep(.el-popper__arrow::before) {
  background-color: var(--card-bg) !important;
  border-color: var(--border-color) !important;
}

:deep(.el-overlay) {
  background-color: rgba(10, 11, 26, 0.7) !important;
}

:deep(.el-tag) {
  border-radius: 16px;
  padding: 4px 12px;
  font-weight: 500;
  font-size: 12px;
  border: none;
}

:deep(.el-tag--success) {
  background: rgba(0, 255, 179, 0.15) !important;
  color: var(--accent-color) !important;
}

:deep(.el-tag--warning) {
  background: rgba(255, 184, 0, 0.15) !important;
  color: #ffb800 !important;
}

:deep(.el-tag--danger) {
  background: rgba(255, 107, 107, 0.15) !important;
  color: #ff6b6b !important;
}

:deep(.el-tag--info) {
  background: rgba(0, 201, 255, 0.15) !important;
  color: var(--secondary-color) !important;
}

:deep(.el-loading-mask) {
  background-color: rgba(10, 11, 26, 0.9);
}

:deep(.el-table .cell) {
  line-height: 1.8;
  white-space: nowrap;
  font-weight: 500;
}

/* 数字或金额列右对齐 */
:deep(.el-table td:nth-child(2), 
       .el-table td:nth-child(3), 
       .el-table td:nth-child(4), 
       .el-table td:nth-child(5), 
       .el-table td:nth-child(6), 
       .el-table td:nth-child(7), 
       .el-table td:nth-child(8)) {
  text-align: right;
}

/* 自定义表格滚动条 */
:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 6px;
  height: 6px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background: var(--border-color);
  border-radius: 10px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
  background: var(--secondary-color);
}

/* 高亮文本和分数样式 */
.highlight-text {
  color: var(--secondary-color);
  font-weight: 600;
}

.money-text {
  color: var(--accent-color);
  font-weight: 600;
}

.score-text {
  display: inline-block;
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  border-radius: 50%;
  font-weight: 600;
}

.r-score {
  background: rgba(0, 255, 179, 0.15);
  color: var(--accent-color);
}

.f-score {
  background: rgba(0, 201, 255, 0.15);
  color: var(--secondary-color);
}

.m-score {
  background: rgba(58, 54, 219, 0.15);
  color: #6236ff;
}

.total-score {
  background: linear-gradient(135deg, rgba(58, 54, 219, 0.15), rgba(0, 201, 255, 0.15));
  color: white;
  width: 36px;
  height: 36px;
  line-height: 36px;
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .charts-section {
    grid-template-columns: 1fr 1fr;
  }
}

@media (max-width: 768px) {
  .navbar {
    padding: 0.8rem 1rem;
    flex-direction: column;
    gap: 1rem;
  }
  
  .nav-items {
    width: 100%;
    justify-content: space-between;
    gap: 0.5rem;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .container {
    padding: 1rem;
  }
  
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }
  
  .table-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }
  
  .search-box {
    width: 100%;
  }
}

/* 修复前往按钮样式 */
:deep(.el-pagination .btn-quicknext),
:deep(.el-pagination .btn-quickprev),
:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next),
:deep(.el-pagination .el-pagination__editor) {
  background-color: rgba(42, 42, 87, 0.4) !important;
  color: var(--text-color) !important;
  border: 1px solid var(--border-color) !important;
}

/* 专门处理前往页码输入框 */
:deep(.el-pagination .el-pagination__jump .el-input) {
  --el-input-bg-color: rgba(42, 42, 87, 0.4) !important;
  margin: 0 0 0 5px !important;
}

:deep(.el-pagination .el-pagination__jump .el-input .el-input__inner) {
  background-color: rgba(42, 42, 87, 0.4) !important;
  color: var(--text-color) !important;
  height: 28px !important;
}

:deep(.el-pagination__jump) {
  color: var(--text-color) !important;
}

:deep(.el-pagination .more),
:deep(.el-pagination button.more::before) {
  background-color: rgba(42, 42, 87, 0.4) !important;
  color: var(--text-color) !important;
}

/* 修复所有跟分页相关的元素 */
:deep(.el-pagination *) {
  background-color: transparent !important;
}

/* 修复10条/页下拉框的白色边框 */
:deep(.el-pagination .el-select .el-input .el-input__wrapper) {
  background-color: rgba(42, 42, 87, 0.4) !important;
  box-shadow: 0 0 0 1px var(--border-color) inset !important;
  border: none !important;
  border-radius: 4px !important;
}

:deep(.el-pagination .el-select .el-input .el-input__wrapper:hover),
:deep(.el-pagination .el-select .el-input .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px var(--secondary-color) inset !important;
}

:deep(.el-pagination .el-select .el-input .el-input__inner) {
  color: var(--text-color) !important;
  height: 28px !important;
}

:deep(.el-select-dropdown__empty) {
  color: var(--text-color) !important;
  background-color: var(--card-bg) !important;
}

/* 添加返回按钮样式 */
.back-button-container {
  padding: 12px 24px;
  background-color: var(--card-bg);
  border-bottom: 1px solid var(--border-color);
}

.back-button {
  display: flex;
  align-items: center;
  gap: 6px;
  background: var(--gradient-primary);
  border: none;
  padding: 6px 16px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 6px rgba(58, 54, 219, 0.3);
}

.back-button:hover {
  box-shadow: 0 4px 12px rgba(58, 54, 219, 0.5);
  transform: translateY(-2px);
}
</style> 